//
//  ArrayList.swift
//  Swift-LeetCode
//
//  Created by 卢悦明 on 2024/1/9.
//

import UIKit


struct StructError: Error {
    var errorMsg: String
}


class ArrayList<Element: Equatable>: NSObject {
    var length: Int
    var elements: Array<Element>
    private let defaultValue: Element
    init(_ length: Int = 10, defaultValue: Element) {
        self.length = 0
        self.defaultValue = defaultValue
        elements = [Element](repeating: defaultValue, count: length)
        
        super.init()
    }

    func size() -> Int {
        return length
    }
    
    func isEmpty() -> Bool {
        length == 0
    }
    
    func add(_ elem: Element) {
        elements[length] = elem
        length += 1
    }
    @discardableResult func remove(_ index: Int) -> Element {
        let removeItem = elements[index]
        for i in index..<length - 1 {
            elements[i] = elements[i+1]
        }
        elements[length - 1] = defaultValue
        length -= 1
        return removeItem
    }
    func insert(_ index: Int, _ elem: Element) {
//        elements.insert(elem, at: index)
        // 从后向前一个一个的向后移动，直到插入的index位置。
        for index in (index...length - 1).reversed() {
            elements[index+1] = elements[index]
        }
        elements[index] = elem
        length += 1
    }
    
    func get(_ index: Int) throws -> Element {
        guard index >= 0 && index < length else {
            throw StructError(errorMsg: "index越界：\(index)")
        }
        return elements[index]
    }
    
    func set(_ index: Int, _ element: Element) throws -> Element {
        guard index >= 0 && index < length else {
            throw StructError(errorMsg: "index越界：\(index)")
        }
        let elem = elements[index]
        elements[index] = element
        return elem
    }
    
    func indexOf(_ elem: Element) -> Int {
        var index = -1
        for item in elements {
            if (item == elem) {
                break
            }
            index += 1
        }
        return index
    }
    
    
    func contains(_ elm: Element) -> Bool {
        let index = indexOf(elm)
        return index != -1
    }
    
    func clear() {
        length = 0
//        elements.removeAll()
        /*
         需要把数组中每个元素清空
         */
        for index in 0..<length {
           elements[index] = defaultValue
        }
        length = 0
    }
    // 数组扩容
    private func arrayKuoRong() {
//        扩容本质是用一个更大的数组去把old数组一个一个的移动到新数组中，OC新数组长度*1.5， java *1.6
    }
    
    func printArray() {
        var str: String = ""
        for item in elements[0..<length] {
            str = str + " \(item)"
        }
        print("************", str)
    }
}
